//
//  HiChatInfoController.m
//  HiCar
//
//  Created by huachun on 2019/3/22.
//  Copyright © 2019 丁一. All rights reserved.
//

#import "HiChatInfoController.h"
#import "HiChatInfoCell.h"
#import "ChatSql.h"
#import "ChatModel.h"
#import "HiJonesClass.h"
#import "HUserIInfoViewModel.h"
#import "HJonesNetting.h"
#import "UserHomeController.h"

@interface HiChatInfoController ()<UITextFieldDelegate,HUserIInfoDelegate,UINavigationControllerDelegate>{
    CGFloat Botton_height;
    
    ChatSql        *sqliteletter;
    
    BOOL           tijiaoOK;
    NSTimer        *timer;
    
    UserModel *linusermo;
}

@property (nonatomic, strong) UIView       *textBG;
@property (nonatomic, strong) UITextField  *Shen_title;

@end

@implementation HiChatInfoController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = _Model.name;
    
    UIBarButtonItem *cancelItem = [[UIBarButtonItem alloc] initWithTitle:@"TA的主页" style:UIBarButtonItemStylePlain target:self action:@selector(go_user)];
    [cancelItem setTintColor:NavItemTitleColor];
    self.navigationItem.rightBarButtonItem = cancelItem;
    
    linusermo = [UserModel info];
    
    if ([linusermo.userid isEqualToString:_Model.userid]) {
        [self goback];
    }
    
    self.Data_array = [NSMutableArray new];
    
    Botton_height = (NAV_Height - 14);
    
    sqliteletter= [[ChatSql alloc] init];
    self.Data_array = [[sqliteletter selectdatanews:_Model.userid] mutableCopy];
    [sqliteletter uadatedata:_Model.userid];
    
    [self.view addSubview:self.TableView];
    self.TableView.emptyDataSetSource   = nil;
    self.TableView.emptyDataSetDelegate = nil;
    self.TableView.backgroundColor=backColor;
    [self.view addSubview:self.textBG];
    self.TableView.frame=CGRectMake(0, 0, RECRWITCH, RECERHEIGHT-Botton_height);
    
    if ([_Model.userid isEqualToString:@"0"]) {
        self.textBG.hidden = YES;
    }
    
    tijiaoOK = NO;
    if (!timer) {
        timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(getXINnews) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
    }
    
    __weak typeof(self)weakSelf = self;
    
    if (weakSelf.Data_array.count>1) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf.TableView
             scrollToRowAtIndexPath:[NSIndexPath
                                     indexPathForRow:weakSelf.Data_array.count-1
                                     inSection:0]
             atScrollPosition:UITableViewScrollPositionBottom
             animated:NO];
        });
    }
}

- (void)go_user{
    UserHomeController *uwerdfsf = [UserHomeController new];
    uwerdfsf.hidesBottomBarWhenPushed = YES;
    uwerdfsf.Model = _Model;
    [self.navigationController pushViewController:uwerdfsf animated:YES];
}

- (void)Succes:(int)value dic:(NSDictionary *)dic{
    if (value==1) {
        tijiaoOK = NO;

        BOOL toblack_user = [[dic objectForKey:@"ToHeiMei"] boolValue];
        if (toblack_user) {
            [SVProgressHUD showErrorWithStatus:@"对不起,对方已将您拉入黑名单!"];
            [self goback];
        }
    }
}

-(void)getXINnews{
    NSMutableArray *linarray = [[sqliteletter selectdatanewstixing:_Model.userid] mutableCopy];
    if (linarray.count>0) {
        for (int i=0; i<linarray.count; i++) {
            ChatModel *model = [linarray objectAtIndex:i];
            [self.Data_array insertObject:model atIndex:self.Data_array.count];
            
            NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.Data_array.count-1 inSection:0];
            [indexPaths addObject:indexPath];
            [self.TableView beginUpdates];
            [self.TableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationBottom];
            [self.TableView endUpdates];
            [self.TableView
             scrollToRowAtIndexPath:[NSIndexPath
                                     indexPathForRow:self.Data_array.count-1
                                     inSection:0]
             atScrollPosition:UITableViewScrollPositionBottom
             animated:YES];

            model.IsRead=@"1";
            [sqliteletter uadatedatadu:model];
        }
    }
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] postNotificationName:CHONGXINTIXINGCOUNT object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [timer invalidate];
    timer = nil;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillhideShow:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    if (!timer) {
        timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(getXINnews) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
    }
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}

- (void)keyboardWillhideShow:(NSNotification *)aNotification{
    [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self->_textBG.frame=CGRectMake(0, RECERHEIGHT-self->Botton_height, RECRWITCH, self->Botton_height);
        self.TableView.frame=CGRectMake(0, 0, RECRWITCH, RECERHEIGHT-self->Botton_height);
    } completion:^(BOOL finished) {
        
    }];
}

- (void)keyboardWillShow:(NSNotification *)aNotification{
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    
    [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self->_textBG.frame=CGRectMake(0, RECERHEIGHT-keyboardRect.size.height-self->Botton_height, RECRWITCH, self->Botton_height);
        self.TableView.frame=CGRectMake(0, 0, RECRWITCH, RECERHEIGHT-self->Botton_height-keyboardRect.size.height);
    } completion:^(BOOL finished) {
        
    }];
    
    if (self.Data_array.count!=0) {
        [self.TableView
         scrollToRowAtIndexPath:[NSIndexPath
                                 indexPathForRow:self.Data_array.count-1
                                 inSection:0]
         atScrollPosition:UITableViewScrollPositionBottom
         animated:YES];
    }
}

-(UIView *)textBG{
    if (!_textBG) {
        _textBG=[[UIView alloc] initWithFrame:CGRectMake(0, RECERHEIGHT-Botton_height, RECRWITCH, Botton_height)];
        _textBG.backgroundColor=[UIColor whiteColor];
        CALayer *line=[CALayer new];
        line.frame=CGRectMake(0, 0, RECRWITCH, 0.5);
        line.backgroundColor=LineColor.CGColor;
        [_textBG.layer addSublayer:line];
        _Shen_title=[self textfield];
        [_Shen_title setValue:[JonesClass stringTOColor:@"#666666"] forKeyPath:@"_placeholderLabel.textColor"];
        _Shen_title.textColor=[UIColor blackColor];
        _Shen_title.frame=CGRectMake(5, 3, RECRWITCH-10-30, 40);
        _Shen_title.returnKeyType = UIReturnKeySend;
        [_textBG addSubview:_Shen_title];
        [_Shen_title addTarget:self action:@selector(passConTextChange:) forControlEvents:UIControlEventEditingChanged];
    }
    return _textBG;
}

-(UITextField *)textfield{
    UITextField *textField=[[UITextField alloc] initWithFrame:CGRectMake(0, 0, RECR.size.width-30, 40)];
    textField.leftViewMode = UITextFieldViewModeAlways;
    textField.leftView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 43)];
    textField.placeholder=@"私信";
    textField.font=[UIFont systemFontOfSize:16];
    textField.autocorrectionType = UITextAutocorrectionTypeNo;
    textField.autocapitalizationType = UITextAutocapitalizationTypeNone;
//    textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    textField.returnKeyType=UIReturnKeyNext;
    textField.layer.borderWidth=0.0;
    textField.backgroundColor=[UIColor clearColor];
    textField.layer.borderColor=[UIColor clearColor].CGColor;
    [textField setValue:[JonesClass stringTOColor:@"#999999"] forKeyPath:@"_placeholderLabel.textColor"];
    textField.textColor=[JonesClass stringTOColor:@"#000000"];
    textField.delegate=self;
    
    CALayer *line=[CALayer new];
    line.frame=CGRectMake(0, 46, RECRWITCH, 0.7);
    line.backgroundColor=LineColor.CGColor;
    [textField.layer addSublayer:line];
    return textField;
}

-(void)passConTextChange:(id)sender{
    UITextField* target=(UITextField*)sender;
    if (target.text.length>100) {
        target.text = [target.text substringToIndex:100];
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self PostPing_lun:nil];
    return YES;
}

-(void)PostPing_lun:(NSString *)img_url{
    
    if (tijiaoOK) {
        return;
    }else{
        tijiaoOK = YES;
    }
    
    if (!img_url) {
        if (_Shen_title.text==nil||[_Shen_title.text isEqualToString:@""]) {
            tijiaoOK = NO;
            return;
        }
    }
    
    NSDate * senddate=[NSDate date];
    NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString * locationString=[dateformatter stringFromDate:senddate];
    
    ChatModel *model=[ChatModel new];
    model.User_id=_Model.userid;
    model.User_name=_Model.name;
    model.User_logo=_Model.logo;
    model.sex=_Model.sex;
    model.briday=_Model.briday;
    model.Chat_date=locationString;
    model.IsRead=@"1";
    
    if (img_url) {
        model.Chat_info=img_url;
        model.Chat_type=@"18";
    }else{
        model.Chat_info=_Shen_title.text;
        model.Chat_type=@"7";
    }
    
    model.Send_type = @"2";
    [sqliteletter Insertdata:model];
    
    if (self.Data_array.count==0) {
        [self.Data_array insertObject:model atIndex:self.Data_array.count];
        [self.TableView reloadData];
    }else{
        [self.Data_array insertObject:model atIndex:self.Data_array.count];
        
        NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.Data_array.count-1 inSection:0];
        [indexPaths addObject:indexPath];
        [self.TableView beginUpdates];
        
        [self.TableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationBottom];
        
        [self.TableView endUpdates];
        
        [self.TableView
         scrollToRowAtIndexPath:[NSIndexPath
                                 indexPathForRow:self.Data_array.count-1
                                 inSection:0]
         atScrollPosition:UITableViewScrollPositionBottom
         animated:YES];
    }
    
    NSMutableDictionary *senddic = [NSMutableDictionary new];
    [senddic setValue:linusermo.userid forKey:@"userid"];
    [senddic setValue:linusermo.name forKey:@"name"];
    
    if (img_url) {
        [senddic setValue:img_url forKey:@"info"];
        [senddic setValue:@"8" forKey:@"type"];
        [SVProgressHUD showWithStatus:@"发送中.."];
    }else{
        [senddic setValue:_Shen_title.text forKey:@"info"];
        [senddic setValue:@"6" forKey:@"type"];
        
        _Shen_title.text = nil;
    }
    
    [senddic setValue:_Model.userid forKey:@"to_userid"];
    
    
    
    [HJonesNetting JonesNetting_POST:senddic
                              andURL:App_Chat_Send
                          andtimeout:30.0
                            finished:^(NSError * _Nonnull error, NSDictionary * _Nonnull resultDict) {
                                self->tijiaoOK = NO;
                                if (error) {
                                    model.Send_type=@"3";
                                    [self->sqliteletter uadatedatatype:model];

                                }else{
                                    if ([[resultDict objectForKey:@"Code"] longLongValue]==1000) {
                                        model.Send_type=@"1";
                                        [self->sqliteletter uadatedatatype:model];
                                        if (self.Data_array.count==0||self.Data_array.count==1){
                                            self.Data_array = [[self->sqliteletter selectdatanews:self->_Model.userid] mutableCopy];
                                        }
                                    }else if ([[resultDict objectForKey:@"Code"] longLongValue]==3000){
                                        model.Send_type=@"5";
                                        [self->sqliteletter uadatedatatype:model];
                                        
                                    }else{
                                        model.Send_type=@"3";
                                        [self->sqliteletter uadatedatatype:model];
                                        
                                    }
                                }
                                [self.TableView reloadData];
                            }
                          passmanger:^(NSURLSessionDataTask * _Nonnull manger) {
                              
                          }
                         andprogress:^(NSProgress * _Nonnull CProgress) {
                             
                         }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.Data_array.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 20;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    ChatModel *Model=[self.Data_array objectAtIndex:indexPath.row];
    
    if ([Model.Chat_type isEqualToString:@"10"]||[Model.Chat_type isEqualToString:@"11"]||[Model.Chat_type isEqualToString:@"20"]) {
        if ([Model.Chat_type isEqualToString:@"10"]||[Model.Chat_type isEqualToString:@"11"]) {
            return 255;
        }
        return 220;
    }
    
    CGFloat linheight = [HiJonesClass getContent:Model.Chat_info width:RECRWITCH/5*3 font:[UIFont systemFontOfSize:15] jianju:3];
    
    if ([Model.Chat_type isEqualToString:@"18"]||[Model.Chat_type isEqualToString:@"8"]) {
        linheight = 140;
    }
    
    if (linheight<30) {
        return linheight+90 + 10;
    }else{
        return linheight+60 + 10;
    }
    return 200;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    ChatModel *Model=[self.Data_array objectAtIndex:indexPath.row];
    
    HiChatInfoCell *cell = [HiChatInfoCell cellForTableView:tableView cellForRowAtIndexPath:indexPath];
    cell.Model = Model;
    cell.selectblock = ^(NSInteger type) {
        [self go_user];
    };

    return cell;
}

@end
